#!/bin/sh
set -o nounset
#set -x #DEBUG

. bin/library.sh

require_iso_rw_mounted

# Exit if nothing to do (ISO RW filesystem has not been modified)
if [ $ISO_DIR/$REMASTER_NAME -nt stamps/isofs.stamp ] ; then exit 0; fi

# Create remastered image from ISO read-write overlay
MKISOFS_UEFI_OPTS=''
ISOHYBRID_UEFI_OPTS=''
if [ "${CONFIG_ISO_UEFI-x}" = "y" ] ; then
    MKISOFS_UEFI_OPTS='-eltorito-alt-boot -e boot/grub/efi.img -no-emul-boot'
    ISOHYBRID_UEFI_OPTS='--uefi'
fi

printinfo Creating remastered ISO image from read-write overlay...
$SUDO $MKISOFS \
    -quiet \
    -D \
    -r \
    -cache-inodes \
    -J \
    -l \
    -c isolinux/boot.cat \
    -b isolinux/isolinux.bin -no-emul-boot -boot-load-size 4 -boot-info-table \
    $MKISOFS_UEFI_OPTS \
    -input-charset utf8 \
    -o $ISO_DIR/$REMASTER_NAME $ISOMNT_RW &&
$SUDO chmod 444 $ISO_DIR/$REMASTER_NAME || die Creating remastered ISO image failed!

# Allow booting either as CD or as HD image
printinfo Converting ISO to hybrid boot...
$SUDO $ISOHYBRID $ISOHYBRID_UEFI_OPTS $ISO_DIR/$REMASTER_NAME || die Unable to make ISO image a hybrid boot!

# Calculate checksums
printinfo Calculating MD5 and SHA256 checksums...
cd $ISO_DIR
md5sum $REMASTER_NAME > md5sums &&
sha256sum $REMASTER_NAME > sha256sums || die Unable to calculate checksums!
cd - >/dev/null

exit 0
